package cn.zhentao.controller;

import cn.zhentao.pojo.Permissions;
import cn.zhentao.pojo.Role;
import cn.zhentao.pojo.User;
import cn.zhentao.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public Result login(@RequestBody Map<String,String> map, HttpServletRequest req){
        System.err.println(map);
        User user1 = userService.login(map.get("userName"),map.get("password"));
        if(user1!=null){
            HttpSession session = req.getSession();
            session.setAttribute("user",user1);
            return new Result(Result.GET_OK,1,"登录成功");
        }else{
            return new Result(Result.GET_ERR,0,"登录失败");
        }
    }

    @RequestMapping("getUserPermissions")
    public Result getUserPermissions(HttpServletRequest request){
        //获取当前用户的id
        User user = (User) request.getSession().getAttribute("user");
        int userId = user.getUserId();
        //获取用户的角色列表
        List<Role> roles = userService.getUserRolesById(userId);
        //根据roleid获取 角色信息
        List<Permissions> permissions = new ArrayList<>();
        for(Role r:roles){
            for(Permissions p:userService.getUserPermissionsByRoleId(r.getRoleId())){
                permissions.add(p);
            }
        }
        return new Result(Result.GET_OK,permissions,"查询成功");
    }
}
